package dto

import (
	"strconv"
	"strings"
	"time"
)

type SyncResultDto struct {
	Phone        string //电话
	Number       string //带+
	JidAccount   string //was账号
	SyncTime     string //同步时间
	TokenPhone   string //Token电话
	TokenCountry string //Token国家
	Timestamp    string //活动时间
	IsIn         bool
	IsBusiness   bool //商业号
	line         string
}

func NewEmptySyncResultDto(phoneStr string) *SyncResultDto {
	phone, number := getPhoneNumber(phoneStr)
	return &SyncResultDto{
		Phone:  phone,
		Number: number,
		IsIn:   false,
	}
}

func NewSyncResultDto(phoneStr, account, syncTime, tokenPhone, tokenCountry, timestamp string, isBusiness bool) *SyncResultDto {
	phone, number := getPhoneNumber(phoneStr)
	return &SyncResultDto{
		Phone:        phone,
		Number:       number,
		JidAccount:   account,
		SyncTime:     syncTime,
		TokenPhone:   tokenPhone,
		TokenCountry: tokenCountry,
		Timestamp:    timestamp,
		IsBusiness:   isBusiness,
		IsIn:         true,
	}
}

func getPhoneNumber(str string) (string, string) {
	phone := strings.TrimPrefix(str, "+")
	number := "+" + phone
	return phone, number
}

func (d *SyncResultDto) GetLine() string {
	if d.line == "" {
		d.line = d.ToWasLine()
	}
	return d.line
}

//有活跃时间
func (d *SyncResultDto) HasActive() bool {
	return d.Timestamp != ""
}

func (d *SyncResultDto) ToWasLine() string {
	//525541121997:5215541121997_1638969379858_6282177980053_id
	if !d.IsIn || d.JidAccount == "" {
		return d.Phone
	}

	var line string
	if strings.Compare(d.Phone, d.JidAccount) == 0 {
		line = d.Phone + ">in"
	} else {
		line = d.Phone + ">" + d.JidAccount
	}
	line += "_" + d.SyncTime + "_" + d.TokenPhone + "_" + d.TokenCountry
	return line
}

func (d *SyncResultDto) FormatTimestamp() string {
	if d.Timestamp == "" {
		return ""
	}
	tsInt, err := strconv.Atoi(d.Timestamp)
	if err != nil {
		return ""
	}
	timestamp := int64(tsInt)
	tsFormat := time.Unix(timestamp, 0).Format("2006-01-02 15:04:05")
	return tsFormat
}
